import { fetchMedifoodDetails } from '../../Service/CategoryService';

Page({
  data: {
    results: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    searchConditions: []
  },

  onLoad(options) {
    this.initializeSearchConditions(options);
    this.loadData();
  },

  initializeSearchConditions(options) {
    const searchConditions = [];
    Object.keys(options).forEach(key => {
      //正则表达式匹配键名中的前缀和索引
      //([a-zA-Z]+): 匹配一个或多个字母，作为前缀。
      //(\d+): 匹配一个或多个数字，作为索引。
      const match = key.match(/([a-zA-Z]+)(\d+)/);
      if (match) {
        const [prefix, index] = match.slice(1, 3);
        if (!searchConditions[index]) {
          searchConditions[index] = {};
        }
        //如果前缀是 value，则对值进行解码。否则，直接使用传入的值
        searchConditions[index][prefix] = prefix === 'value' ? decodeURIComponent(options[key]) : options[key];
      }
    });
    this.setData({ searchConditions });
  },

  async loadData() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });

    try {
      const searchConditions = this.data.searchConditions;
      const searchResults = await fetchMedifoodDetails(searchConditions, this.data.page, this.data.pageSize);

      this.setData({
        results: this.data.page === 1 ? searchResults : this.data.results.concat(searchResults),
        hasMore: searchResults.length === this.data.pageSize,
        loading: false
      });
    } catch (error) {
      console.error('获取搜索结果失败:', error);
      this.setData({ loading: false });
    }
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({ page: this.data.page + 1 });
      setTimeout(() => {
        this.loadData();
       }, 1000);
    }
  }
});
